<template>
  <div class="online-appointments">
    <a-card title="线上约面管理" :bordered="false" class="appointments-card">
      <template #title>
        <div class="card-title">
          <a-button type="link" class="back-button" @click="router.back()">
            <arrow-left-outlined />
          </a-button>
          <span>线上约面管理</span>
        </div>
      </template>
      <template #extra>
        <div class="filter-actions">
          <a-input-search
            v-model:value="searchText"
            placeholder="搜索应聘者姓名"
            style="width: 200px; margin-right: 16px"
            @search="handleSearch"
          />
          <a-select
            v-model:value="filterStatus"
            placeholder="约面状态"
            style="width: 120px"
            @change="handleFilterChange"
          >
            <a-select-option value="">全部状态</a-select-option>
            <a-select-option value="0">待回应</a-select-option>
            <a-select-option value="1">已拒绝</a-select-option>
            <a-select-option value="2">已接受</a-select-option>
          </a-select>
        </div>
      </template>

      <!-- 约面记录表格 -->
      <a-table
        :columns="columns"
        :data-source="filteredAppointments"
        :loading="loading"
        :pagination="{ pageSize: 10 }"
        :row-key="(record) => record.id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'candidate'">
            <div>
              <div style="font-weight: 500">{{ record.userName }}</div>
              <div style="font-size: 12px; color: #999">{{ record.userEmail }}</div>
            </div>
          </template>

          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.isAccepted)">
              {{ getStatusText(record.isAccepted) }}
            </a-tag>
          </template>

          <template v-if="column.key === 'action'">
            <div class="action-buttons">
              <a-button type="link" @click="viewDetail(record)">查看详情</a-button>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 约面详情弹窗 -->
    <a-modal v-model:visible="detailModalVisible" title="约面详情" :footer="null" width="600px">
      <template v-if="selectedAppointment">
        <div class="appointment-detail-header">
          <div class="candidate-info">
            <h3>{{ selectedAppointment.userName }}</h3>
            <p>{{ selectedAppointment.userEmail }}</p>
            <p>应聘岗位：{{ selectedAppointment.position }}</p>
          </div>
          <div class="appointment-status">
            <a-tag :color="getStatusColor(selectedAppointment.isAccepted)">
              {{ getStatusText(selectedAppointment.isAccepted) }}
            </a-tag>
          </div>
        </div>

        <a-divider />

        <a-descriptions bordered :column="1">
          <a-descriptions-item label="面试公司">
            {{ selectedAppointment.company }}
          </a-descriptions-item>
          <a-descriptions-item label="技术领域">
            {{ selectedAppointment.techField }}
          </a-descriptions-item>
          <a-descriptions-item label="约面时间">
            {{ selectedAppointment.interviewTime }}
          </a-descriptions-item>
          <a-descriptions-item label="腾讯会议码">
            <div class="meeting-code-container">
              <span class="meeting-code">{{ selectedAppointment.txMeetingCode }}</span>
              <a-button
                type="link"
                size="small"
                class="copy-btn"
                @click="copyMeetingCode(selectedAppointment.txMeetingCode)"
              >
                <copy-outlined /> 复制
              </a-button>
            </div>
          </a-descriptions-item>
          <a-descriptions-item label="面试官">
            {{ selectedAppointment.interviewerName }}
          </a-descriptions-item>
          <a-descriptions-item v-if="selectedAppointment.rejectReason" label="拒绝原因">
            {{ selectedAppointment.rejectReason }}
          </a-descriptions-item>
          <a-descriptions-item v-if="selectedAppointment.notes" label="备注">
            {{ selectedAppointment.notes }}
          </a-descriptions-item>
        </a-descriptions>

        <div class="modal-footer">
          <a-button @click="detailModalVisible = false">关闭</a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { ArrowLeftOutlined, CopyOutlined } from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/useLoginUserstore'
import { recruiterViewOnlineInterviewListUsingGet } from '@/api/commonController'

const router = useRouter()
const userStore = useLoginUserStore()

// 表格列定义
const columns = [
  {
    title: '应聘者',
    dataIndex: 'userName',
    key: 'candidate',
    width: '20%',
  },
  {
    title: '应聘岗位',
    dataIndex: 'position',
    key: 'position',
    width: '15%',
  },
  {
    title: '约面时间',
    dataIndex: 'interviewTime',
    key: 'interviewTime',
    width: '20%',
    sorter: (a, b) => Number(new Date(a.interviewTime)) - Number(new Date(b.interviewTime)),
  },
  {
    title: '发送时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: '15%',
  },
  {
    title: '状态',
    dataIndex: 'isAccepted',
    key: 'status',
    width: '10%',
  },
  {
    title: '操作',
    key: 'action',
    width: '20%',
  },
]

// 约面记录数据
const appointments = ref([])

// 筛选和搜索状态
const searchText = ref('')
const filterStatus = ref('')
const loading = ref(false)

// 模态框状态
const detailModalVisible = ref(false)
const selectedAppointment = ref(null)

// 筛选后的记录
const filteredAppointments = computed(() => {
  return appointments.value.filter((record) => {
    // 搜索名称或邮箱
    const searchMatch =
      record.userName.toLowerCase().includes(searchText.value.toLowerCase()) ||
      record.userEmail.toLowerCase().includes(searchText.value.toLowerCase())

    // 筛选状态
    const statusMatch = filterStatus.value ? String(record.isAccepted) === filterStatus.value : true

    return searchMatch && statusMatch
  })
})

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待回应',
    1: '已拒绝',
    2: '已接收',
  }
  return statusMap[status] || '未知状态'
}

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    0: 'blue',
    1: 'error',
    2: 'success',
  }
  return colorMap[status] || 'default'
}

// 处理搜索
const handleSearch = () => {
  // 使用本地筛选，已通过computed实现
}

// 处理筛选变化
const handleFilterChange = () => {
  // 使用本地筛选，已通过computed实现
}

// 查看详情
const viewDetail = (record) => {
  selectedAppointment.value = record
  detailModalVisible.value = true
}

//获取线上邀请记录
const fetchOnlineInterviewList = async () => {
  const company = userStore.loginUser?.company
  loading.value = true

  if (company) {
    try {
      const response = await recruiterViewOnlineInterviewListUsingGet({
        company: company,
      })

      if (response && response.data) {
        appointments.value = response.data as any
        console.log('获取线上邀请记录成功:', response.data)
      } else {
        message.error('获取线上邀请记录失败')
      }
    } catch (error) {
      console.error('获取线上邀请记录失败：', error)
      message.error('获取线上邀请记录失败')
    }
  }
  loading.value = false
}

// 组件挂载时获取数据
onMounted(async () => {
  await fetchOnlineInterviewList()
})

// 复制会议码
const copyMeetingCode = (code) => {
  if (navigator.clipboard) {
    navigator.clipboard
      .writeText(code)
      .then(() => {
        message.success('会议码已复制到剪贴板')
      })
      .catch(() => {
        message.error('复制失败，请手动复制')
      })
  } else {
    // 兼容不支持 clipboard API 的浏览器
    const textarea = document.createElement('textarea')
    textarea.value = code
    textarea.style.position = 'fixed'
    textarea.style.opacity = '0'
    document.body.appendChild(textarea)
    textarea.select()

    try {
      const successful = document.execCommand('copy')
      if (successful) {
        message.success('会议码已复制到剪贴板')
      } else {
        message.error('复制失败，请手动复制')
      }
    } catch (err) {
      message.error('复制失败，请手动复制')
    }

    document.body.removeChild(textarea)
  }
}
</script>

<style scoped>
.online-appointments {
  padding: 24px;
  background: #f0f2f5;
  min-height: calc(100vh - 64px);
}

.appointments-card {
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
}

.card-title {
  display: flex;
  align-items: center;
}

.back-button {
  margin-right: 12px;
  font-size: 18px;
  padding: 0;
  color: #1890ff;
}

.filter-actions {
  display: flex;
  align-items: center;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

/* 约面详情样式 */
.appointment-detail-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;
}

.candidate-info h3 {
  margin: 0 0 8px 0;
}

.candidate-info p {
  margin: 0 0 4px 0;
  color: #666;
}

.appointment-status {
  text-align: right;
}

/* 会议信息样式 */
.meeting-qrcode {
  text-align: center;
  margin-bottom: 24px;
}

.qrcode-image {
  width: 200px;
  height: 200px;
}

.meeting-info {
  background: #f9f9f9;
  padding: 16px;
  border-radius: 4px;
  margin-bottom: 24px;
}

.meeting-info h3 {
  margin-top: 0;
  margin-bottom: 16px;
  color: #1890ff;
}

.meeting-info p {
  margin-bottom: 8px;
}

.modal-footer {
  text-align: right;
}

.meeting-code-container {
  display: flex;
  align-items: center;
}

.meeting-code {
  margin-right: 8px;
}

.copy-btn {
  padding: 0;
}
</style>
